#!/usr/bin/env python3
"""
AI日志分析系统启动脚本
"""

import os
import sys
import subprocess
import time
import requests
from pathlib import Path

def check_python_version():
    """检查Python版本"""
    if sys.version_info < (3, 8):
        print("❌ 错误: 需要Python 3.8或更高版本")
        sys.exit(1)
    print("✅ Python版本检查通过")

def install_dependencies():
    """安装依赖"""
    print("📦 安装Python依赖...")
    try:
        subprocess.run([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"], 
                      check=True, capture_output=True)
        print("✅ Python依赖安装完成")
    except subprocess.CalledProcessError as e:
        print(f"❌ Python依赖安装失败: {e}")
        sys.exit(1)

def install_frontend_dependencies():
    """安装前端依赖"""
    print("📦 安装前端依赖...")
    frontend_dir = Path("frontend")
    if not frontend_dir.exists():
        print("❌ 前端目录不存在")
        return False
    
    try:
        os.chdir(frontend_dir)
        subprocess.run(["npm", "install"], check=True, capture_output=True)
        os.chdir("..")
        print("✅ 前端依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"❌ 前端依赖安装失败: {e}")
        return False
    except FileNotFoundError:
        print("❌ 未找到npm，请先安装Node.js")
        return False

def create_directories():
    """创建必要的目录"""
    directories = ["uploads", "temp", "config"]
    for directory in directories:
        Path(directory).mkdir(exist_ok=True)
    print("✅ 目录创建完成")

def check_ai_config():
    """检查AI配置"""
    config_file = Path("config/ai_config.json")
    if not config_file.exists():
        print("⚠️  AI配置文件不存在，将使用默认配置")
        return False
    
    try:
        import json
        with open(config_file, 'r', encoding='utf-8') as f:
            config = json.load(f)
        
        provider = config.get('provider', 'openai')
        
        if provider == 'local':
            # 检查本地模型服务
            try:
                import requests
                response = requests.get("http://localhost:1234/v1/models", timeout=5)
                if response.status_code == 200:
                    print("✅ 本地LM模型服务检查通过")
                    return True
                else:
                    print("⚠️  本地LM模型服务未响应")
                    print("   请确保LM Studio或其他本地模型服务正在运行")
                    return False
            except:
                print("⚠️  本地LM模型服务未启动")
                print("   请启动LM Studio或其他本地模型服务")
                print("   默认地址: http://localhost:1234")
                return False
        else:
            # 检查云服务API密钥
            if not config.get('api_key'):
                print("⚠️  请配置AI API密钥")
                print("   1. 编辑 config/ai_config.json")
                print("   2. 设置您的API密钥")
                return False
            
            print("✅ AI配置检查通过")
            return True
    except Exception as e:
        print(f"❌ AI配置检查失败: {e}")
        return False

def start_backend():
    """启动后端服务"""
    print("🚀 启动后端服务...")
    try:
        # 启动Flask应用
        process = subprocess.Popen([
            sys.executable, "app.py"
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        
        # 等待服务启动
        time.sleep(3)
        
        # 检查服务是否启动成功
        try:
            response = requests.get("http://localhost:8080/", timeout=5)
            if response.status_code == 200:
                print("✅ 后端服务启动成功 (http://localhost:8080)")
                return process
        except requests.RequestException:
            pass
        
        print("❌ 后端服务启动失败")
        return None
    except Exception as e:
        print(f"❌ 启动后端服务时出错: {e}")
        return None

def start_frontend():
    """启动前端服务"""
    print("🚀 启动前端服务...")
    try:
        os.chdir("frontend")
        process = subprocess.Popen([
            "npm", "run", "dev"
        ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        os.chdir("..")
        
        # 等待服务启动
        time.sleep(5)
        
        print("✅ 前端服务启动成功 (http://localhost:5173)")
        return process
    except Exception as e:
        print(f"❌ 启动前端服务时出错: {e}")
        return None

def main():
    """主函数"""
    print("🤖 AI日志分析系统启动器")
    print("=" * 50)
    
    # 检查Python版本
    check_python_version()
    
    # 安装依赖
    install_dependencies()
    
    # 安装前端依赖
    if not install_frontend_dependencies():
        print("⚠️  前端依赖安装失败，将只启动后端服务")
    
    # 创建目录
    create_directories()
    
    # 检查AI配置
    ai_config_ok = check_ai_config()
    
    # 启动后端
    backend_process = start_backend()
    if not backend_process:
        print("❌ 系统启动失败")
        sys.exit(1)
    
    # 启动前端
    frontend_process = None
    if Path("frontend").exists():
        frontend_process = start_frontend()
    
    print("\n" + "=" * 50)
    print("🎉 系统启动完成!")
    print("\n访问地址:")
    print("  后端API: http://localhost:8080")
    if frontend_process:
        print("  前端界面: http://localhost:5173")
    print("\n使用说明:")
    print("  1. 打开浏览器访问前端地址")
    print("  2. 上传日志文件(.tar.gz格式)")
    print("  3. 进入'AI助手'页面进行智能分析")
    if not ai_config_ok:
        print("  4. 配置AI服务以启用AI功能")
        print("     - 云服务: 配置API密钥")
        print("     - 本地模型: 启动LM Studio等服务")
    print("\n按 Ctrl+C 停止服务")
    print("=" * 50)
    
    try:
        # 等待用户中断
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n🛑 正在停止服务...")
        
        # 停止后端
        if backend_process:
            backend_process.terminate()
            backend_process.wait()
            print("✅ 后端服务已停止")
        
        # 停止前端
        if frontend_process:
            frontend_process.terminate()
            frontend_process.wait()
            print("✅ 前端服务已停止")
        
        print("👋 系统已安全停止")

if __name__ == "__main__":
    main() 